package com.pethospital.servlet;

import com.pethospital.entity.User;
import com.pethospital.entity.Pet;
import com.pethospital.entity.Appointment;
import com.pethospital.entity.HealthRecord;
import com.pethospital.service.PetService;
import com.pethospital.service.AppointmentService;
import com.pethospital.service.HealthRecordService;
import com.pethospital.service.UserService;
import com.pethospital.service.impl.PetServiceImpl;
import com.pethospital.service.impl.AppointmentServiceImpl;
import com.pethospital.service.impl.HealthRecordServiceImpl;
import com.pethospital.service.impl.UserServiceImpl;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.List;

/**
 * 数据导出控制器
 * Export Controller Servlet
 * 
 * @author PetHospital System
 * @version 1.0
 */
public class ExportServlet extends HttpServlet {
    
    private PetService petService = new PetServiceImpl();
    private AppointmentService appointmentService = new AppointmentServiceImpl();
    private HealthRecordService healthRecordService = new HealthRecordServiceImpl();
    private UserService userService = new UserServiceImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        // 检查管理员权限
        HttpSession session = request.getSession();
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null || !"admin".equals(currentUser.getUserType())) {
            response.sendRedirect(request.getContextPath() + "/pages/common/unauthorized.jsp");
            return;
        }
        
        // 从URL路径获取操作类型
        String pathInfo = request.getPathInfo();
        String action = pathInfo != null ? pathInfo.substring(1) : "";
        
        try {
            switch (action) {
                case "pets":
                    handleExportPets(request, response);
                    break;
                case "users":
                    handleExportUsers(request, response);
                    break;
                case "health-records":
                    handleExportHealthRecords(request, response);
                    break;
                case "appointments":
                    handleExportAppointments(request, response);
                    break;
                default:
                    response.sendError(HttpServletResponse.SC_BAD_REQUEST, "无效的导出类型");
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出失败");
        }
    }
    
    /**
     * 导出宠物数据
     */
    private void handleExportPets(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        try {
            // 获取所有宠物数据
            List<Pet> pets = petService.exportPets(null);
            
            // 创建Excel工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("宠物数据");
            
            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] headers = {"宠物ID", "宠物姓名", "宠物类型", "品种", "性别", "年龄(月)", "体重(kg)", "毛色", "健康状态", "主人姓名", "注册时间"};
            
            // 设置标题样式
            CellStyle headerStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);
            headerStyle.setFillForegroundColor(IndexedColors.LIGHT_BLUE.getIndex());
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
            }
            
            // 填充数据
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (int i = 0; i < pets.size(); i++) {
                Pet pet = pets.get(i);
                Row row = sheet.createRow(i + 1);
                
                row.createCell(0).setCellValue(pet.getPetId() != null ? pet.getPetId() : 0);
                row.createCell(1).setCellValue(pet.getPetName() != null ? pet.getPetName() : "");
                row.createCell(2).setCellValue(pet.getPetType() != null ? pet.getPetType() : "");
                row.createCell(3).setCellValue(pet.getBreed() != null ? pet.getBreed() : "");
                row.createCell(4).setCellValue(pet.getGender() != null ? pet.getGender() : "");
                row.createCell(5).setCellValue(pet.getAge() != null ? pet.getAge() : 0);
                row.createCell(6).setCellValue(pet.getWeight() != null ? pet.getWeight().doubleValue() : 0.0);
                row.createCell(7).setCellValue(pet.getColor() != null ? pet.getColor() : "");
                row.createCell(8).setCellValue(pet.getStatus() != null ? pet.getStatus() : "");
                row.createCell(9).setCellValue(pet.getOwner() != null ? pet.getOwner().getRealName() : "");
                row.createCell(10).setCellValue(pet.getCreateTime() != null ? dateFormat.format(pet.getCreateTime()) : "");
            }
            
            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }
            
            // 设置响应头
            String fileName = URLEncoder.encode("宠物数据导出_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new java.util.Date()) + ".xlsx", "UTF-8");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            
            // 写入响应
            OutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            workbook.close();
            outputStream.flush();
            outputStream.close();
            
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出宠物数据失败");
        }
    }
    
    /**
     * 导出预约数据
     */
    private void handleExportAppointments(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        try {
            // 获取所有预约数据
            List<Appointment> appointments = appointmentService.exportAppointments(null);
            
            // 创建Excel工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("预约数据");
            
            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] headers = {"预约ID", "宠物姓名", "主人姓名", "预约日期", "预约时间", "服务类型", "状态", "医生", "备注"};
            
            // 设置标题样式
            CellStyle headerStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);
            headerStyle.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
            
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
            }
            
            // 填充数据
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            for (int i = 0; i < appointments.size(); i++) {
                Appointment appointment = appointments.get(i);
                Row row = sheet.createRow(i + 1);
                
                row.createCell(0).setCellValue(appointment.getAppointmentId() != null ? appointment.getAppointmentId() : 0);
                row.createCell(1).setCellValue(appointment.getPet() != null ? appointment.getPet().getPetName() : "");
                row.createCell(2).setCellValue(appointment.getOwner() != null ? appointment.getOwner().getRealName() : "");
                row.createCell(3).setCellValue(appointment.getAppointmentDate() != null ? dateFormat.format(appointment.getAppointmentDate()) : "");
                row.createCell(4).setCellValue(appointment.getAppointmentTime() != null ? appointment.getAppointmentTime().toString() : "");
                row.createCell(5).setCellValue(appointment.getServiceType() != null ? appointment.getServiceType() : "");
                row.createCell(6).setCellValue(appointment.getStatus() != null ? appointment.getStatus() : "");
                row.createCell(7).setCellValue(appointment.getDoctorName() != null ? appointment.getDoctorName() : "");
                row.createCell(8).setCellValue(appointment.getNotes() != null ? appointment.getNotes() : "");
            }
            
            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }
            
            // 设置响应头
            String fileName = URLEncoder.encode("预约数据导出_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new java.util.Date()) + ".xlsx", "UTF-8");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            
            // 写入响应
            OutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            workbook.close();
            outputStream.flush();
            outputStream.close();
            
        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出预约数据失败");
        }
    }

    /**
     * 导出用户数据
     */
    private void handleExportUsers(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {
            // 获取所有用户数据
            List<User> users = userService.getAllUsers();

            // 创建Excel工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("用户数据");

            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] headers = {"用户ID", "用户名", "真实姓名", "用户类型", "手机号", "邮箱", "地址", "状态", "注册时间"};

            // 设置标题样式
            CellStyle headerStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);
            headerStyle.setFillForegroundColor(IndexedColors.LIGHT_YELLOW.getIndex());
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
            }

            // 填充数据
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (int i = 0; i < users.size(); i++) {
                User user = users.get(i);
                Row row = sheet.createRow(i + 1);

                row.createCell(0).setCellValue(user.getUserId() != null ? user.getUserId() : 0);
                row.createCell(1).setCellValue(user.getUsername() != null ? user.getUsername() : "");
                row.createCell(2).setCellValue(user.getRealName() != null ? user.getRealName() : "");
                row.createCell(3).setCellValue(user.getUserType() != null ? user.getUserType() : "");
                row.createCell(4).setCellValue(user.getPhone() != null ? user.getPhone() : "");
                row.createCell(5).setCellValue(user.getEmail() != null ? user.getEmail() : "");
                row.createCell(6).setCellValue(user.getAddress() != null ? user.getAddress() : "");
                row.createCell(7).setCellValue(user.getStatus() != null ? user.getStatus() : "");
                row.createCell(8).setCellValue(user.getCreateTime() != null ? dateFormat.format(user.getCreateTime()) : "");
            }

            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }

            // 设置响应头
            String fileName = URLEncoder.encode("用户数据导出_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new java.util.Date()) + ".xlsx", "UTF-8");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

            // 写入响应
            OutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            workbook.close();
            outputStream.flush();
            outputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出用户数据失败");
        }
    }

    /**
     * 导出健康记录数据
     */
    private void handleExportHealthRecords(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        try {
            // 获取所有健康记录数据
            List<HealthRecord> healthRecords = healthRecordService.getAllHealthRecords();

            // 创建Excel工作簿
            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet("健康记录数据");

            // 创建标题行
            Row headerRow = sheet.createRow(0);
            String[] headers = {"记录ID", "宠物姓名", "就诊日期", "症状", "诊断", "治疗方案", "药物", "医生", "费用", "下次复诊日期", "备注"};

            // 设置标题样式
            CellStyle headerStyle = workbook.createCellStyle();
            Font headerFont = workbook.createFont();
            headerFont.setBold(true);
            headerStyle.setFont(headerFont);
            headerStyle.setFillForegroundColor(IndexedColors.LIGHT_ORANGE.getIndex());
            headerStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
                cell.setCellStyle(headerStyle);
            }

            // 填充数据
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            for (int i = 0; i < healthRecords.size(); i++) {
                HealthRecord record = healthRecords.get(i);
                Row row = sheet.createRow(i + 1);

                row.createCell(0).setCellValue(record.getRecordId() != null ? record.getRecordId() : 0);
                row.createCell(1).setCellValue(record.getPet() != null ? record.getPet().getPetName() : "");
                row.createCell(2).setCellValue(record.getVisitDate() != null ? dateFormat.format(record.getVisitDate()) : "");
                row.createCell(3).setCellValue(record.getSymptoms() != null ? record.getSymptoms() : "");
                row.createCell(4).setCellValue(record.getDiagnosis() != null ? record.getDiagnosis() : "");
                row.createCell(5).setCellValue(record.getTreatment() != null ? record.getTreatment() : "");
                row.createCell(6).setCellValue(record.getMedication() != null ? record.getMedication() : "");
                row.createCell(7).setCellValue(record.getDoctorName() != null ? record.getDoctorName() : "");
                row.createCell(8).setCellValue(record.getCost() != null ? record.getCost().doubleValue() : 0.0);
                row.createCell(9).setCellValue(record.getNextVisitDate() != null ? dateFormat.format(record.getNextVisitDate()) : "");
                row.createCell(10).setCellValue(record.getNotes() != null ? record.getNotes() : "");
            }

            // 自动调整列宽
            for (int i = 0; i < headers.length; i++) {
                sheet.autoSizeColumn(i);
            }

            // 设置响应头
            String fileName = URLEncoder.encode("健康记录导出_" + new SimpleDateFormat("yyyyMMdd_HHmmss").format(new java.util.Date()) + ".xlsx", "UTF-8");
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

            // 写入响应
            OutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            workbook.close();
            outputStream.flush();
            outputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "导出健康记录数据失败");
        }
    }
}
